package com.kingsoft.dc.khaos.dsl.utils;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.Serializable;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class JsonUtils implements Serializable {
    static ObjectMapper objectMapper = new ObjectMapper();

    static {
        objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    }

    @SuppressWarnings({"unchecked", "rawtypes"})
    public static <T> T json2object(String _json, Class cls) throws JsonParseException, JsonMappingException, IOException {
        return (T) objectMapper.readValue(_json, cls);
    }


    public static String object2json(Object obj) throws JsonProcessingException {
        return objectMapper.writeValueAsString(obj);
    }

    public static Map<String, String> tenantIdMap (InputStream in) throws Exception {
        HashMap<String, String> tenantsMap = new HashMap<>();

        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        byte[] data = new byte[4096];
        int count = -1;
        while ((count = in.read(data)) != -1)
            outStream.write(data, 0, count);
        data = null;
//        return new String(outStream.toByteArray());
        HashMap<String, Object> result = JsonUtils.json2object(new String(outStream.toByteArray()), HashMap.class);
        if (result.containsKey("users")) {
            System.out.println(result.get("users"));
            List<HashMap<String, Object>> list = (List<HashMap<String, Object>>) (result.get("users"));
            for (Map<String, Object> map : list) {
                String id = (String) map.get("tenantId");
                String name = (String) map.get("name");
                tenantsMap.put(id, name);
            }
        }
        return tenantsMap;

    }
}
